package com.onlygx.dva.config.annotation.user;

import com.onlygx.dva.common.entity.dto.CoreUserDTO;
import com.onlygx.dva.common.utils.OpenTelemetryLogUtils;
import com.onlygx.dva.common.utils.RequestLogUtil;
import lombok.RequiredArgsConstructor;
import org.springframework.core.MethodParameter;
import org.springframework.stereotype.Component;
import org.springframework.web.bind.support.WebDataBinderFactory;
import org.springframework.web.context.request.NativeWebRequest;
import org.springframework.web.method.support.HandlerMethodArgumentResolver;
import org.springframework.web.method.support.ModelAndViewContainer;

import javax.annotation.Nonnull;
import javax.servlet.http.HttpServletRequest;

/**
 * <p>
 * 用户信息
 * </p>
 *
 * @author 高祥
 * @version 1.0.0
 * @since 2023年7月31日10:40:18
 */
@Component
@RequiredArgsConstructor
public class DevUserHandlerMethodArgumentResolver implements HandlerMethodArgumentResolver {

    @Override
    public boolean supportsParameter(MethodParameter parameter) {
        return parameter.getParameterType().isAssignableFrom(CoreUserDTO.class)
                && parameter.hasParameterAnnotation(CoreUser.class);
    }

    @Override
    public Object resolveArgument(@Nonnull MethodParameter parameter, ModelAndViewContainer container,
                                  NativeWebRequest request, WebDataBinderFactory factory) {
        //打日志
        String agent = request.getHeader("Traceparent");
        OpenTelemetryLogUtils.showInfo(agent,"获取用户信息");

        HttpServletRequest  httpRequest = request.getNativeRequest(HttpServletRequest.class);
        CoreUserDTO userDTO = null;
        if (httpRequest != null) {
            userDTO = RequestLogUtil.getRequestUser(httpRequest);
        }
        return userDTO;
    }
}
